package com.hbnu.system.config;


import com.hbnu.system.core.base.Rest;
import com.hbnu.system.core.base.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.util.List;

/**
 * @Author: cyj
 * @DateTime: 2021/10/19 10:03
 **/
@Slf4j
@ResponseBody
@RestControllerAdvice
public class CascExceptionHandler {


    /**
     * BaseException 异常捕获处理
     *
     * @param ex 自定义BaseException异常类型
     * @return Result
     */
    @ExceptionHandler(value = {BaseException.class})
    @ResponseStatus(HttpStatus.OK)
    public Rest<?> handleException(BaseException ex) {
        log.error("BaseException 程序异常：" + ex.toString());
        return Rest.failed(ex.getMessage());
    }


    /**
     * NullPointerException 空指针异常捕获处理
     *
     * @param ex 自定义NullPointerException异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Rest<?> handleException(NullPointerException ex) {
        log.error("程序异常NullPointerException：", ex);
        return Rest.failed(ex.getMessage());
    }


    /**
     * validation Exception
     *
     * @param exception MethodArgumentNotValidException
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
//     @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Rest<String> handleBodyValidException(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
        return Rest.failed(ResultCode.VALIDATE_FAILED, fieldErrors.get(0).getDefaultMessage());
    }

    @ExceptionHandler(MultipartException.class)
    public Rest<String> uploadException(MultipartException ex){
        log.error("文件上传大小超出限制MultipartException：" + ex.toString());
        return Rest.failed("文件上传大小超出限制");
    }


}
